package com.jy.wms.service;

import com.jy.wms.common.UUIDUtils;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SetAndModifyModel;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
    * @ClassName: WmsSplitService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Liyi
    * @Date Tue Oct 24 15:29:46 CST 2017
    */

    @Service
    public class WmsSplitService extends BaseService<WmsSplitMapper,WmsSplit> {

    @Autowired
    private WmsGoodsMapper wmsGoodsMapper;
    @Autowired
    private WmsSplitHistoryMapper wmsSplitHistoryMapper;
    @Autowired
    private WmsShipmentOrderMapper wmsShipmentOrderMapper;

     /**
     * 插入一条记录
     * @param entity 实体对象
     * @return int
     */
    public Integer baseInsert( WmsSplit entity){
         return dao.baseInsert( entity );
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective( WmsSplit entity){
         return dao.baseInsertSelective( entity);
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey( String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

    /**
     *  删除（根据所属发运订单ID删除所属明细）
     * @param setAndModifyModel 所属发运订单ID
     * @return
     */
    @BaseServiceDescribe(moduleName = "拆单操作",btnName = "取消拆单")
    public Integer baseDeleteBySsfyddid( SetAndModifyModel setAndModifyModel,String cdr,String ckid)throws Exception{
        List<String> list = setAndModifyModel.getIds();
        //拆单表内已有发运订单的liet
        List<String> cdCount =  dao.getCdCount(list);
        WmsShipmentOrder wmsShipmentOrder = new WmsShipmentOrder();
        StringBuffer errMessage = new StringBuffer();
        Integer errCount = 0;
        //根据采购订单IDS删除拆单数据
        dao.baseDeleteBySsfyddid(cdCount);
        //根据采购订单IDS修改采购订单拆单状态
        dao.updateShipmentOrderQxCdzt(cdCount);
        //删除原有的拆单历史记录
        wmsSplitHistoryMapper.baseDeleteBathPrimarySsfyddid(cdCount);
        //写入取消拆单历史记录
        for (String s : cdCount) {
            //新增拆单历史
            WmsSplitHistory wmsSplitHistory = new WmsSplitHistory();
            wmsSplitHistory.setId(UUIDUtils.uuid());
            wmsSplitHistory.setSsfyddid(s);
            wmsSplitHistory.setCdr(cdr);
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wmsSplitHistory.setCdsj(sdf.format(new Date()));
            wmsSplitHistory.setCzlx("1");
            wmsSplitHistory.setCkid(ckid);
            wmsSplitHistoryMapper.insert(wmsSplitHistory);
        }
        for (String s : list) {
            if(!cdCount.contains(s)){
                wmsShipmentOrder = wmsShipmentOrderMapper.selectById(s);
                if(errMessage.length() > 0){
                    errMessage.append("," + wmsShipmentOrder.getFybh());
                }else{
                    errMessage.append(",失败单号：" + wmsShipmentOrder.getFybh());
                }
                errCount++;
            }
        }
        throw new SucessException("取消拆单操作，成功"+cdCount.size()+ "条" + (errCount > 0 ? "失败"+ errCount + "条"+errMessage.toString()+"请确定发运订单已拆单": ""));
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys( List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsSplit>
    */
    public Page<Map<String,Object>> baseSelectPage(WmsSplit entity ){
        PageHelper.startPage(entity.getPage(),entity.getRows());
        return (Page<Map<String,Object>>)dao.baseSelectPage( entity );
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsSplit
    */
    public WmsSplit baseSelectByPrimaryKey( String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys( List<WmsSplit> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKeySelective( WmsSplit entity){
         return dao.baseUpdateByPrimaryKeySelective( entity);
    }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey( WmsSplit entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }

    /**
     * 拆单
     * @param setAndModifyModel 所属发运订单ID列表
     * @return 0 成功 1订单未审核不可拆单
     */
    @BaseServiceDescribe(moduleName = "拆单操作",btnName = "拆单")
    @Transactional
    public void split(SetAndModifyModel setAndModifyModel,String cdr, String ckid)throws Exception{
            StringBuffer errMessage = new StringBuffer();
            //未拆单 已审核的IDS
            List<String> wcdIds = dao.getWcdCount(setAndModifyModel.getIds());
            //已拆单 或 未审核 的IDS
            List<String> ycdIds = dao.getYcdCount(setAndModifyModel.getIds());
            WmsShipmentOrder wmsShipmentOrder = new WmsShipmentOrder();
            for (String s : wcdIds) {
                wmsShipmentOrder.setId(s);
                //获取发运订单明细列表
                List<WmsShipmentOrderDetailed> shipmentDetList = dao.baseSelectBySsfyddid(s);
                for (WmsShipmentOrderDetailed wmsShipmentOrderDetailed : shipmentDetList) {
                    Integer yqsl = Integer.valueOf(wmsShipmentOrderDetailed.getYqsl());
                    //创建拆单表实体并且加入发运订单ID
                    WmsSplit wmsSplit = new WmsSplit();
                    wmsSplit.setSsfyddid(s);
                    //找到对应的货品包装
                    WmsGoods wmsGoods = wmsGoodsMapper.baseSelectByPrimaryKey(wmsShipmentOrderDetailed.getHpid());
                    //找到的包装根据包装类型正序排序
                    List<WmsPackingDetailed> packingDetailedList = dao.selectPackingDetailedByBzid(wmsGoods.getBzid());
                    //箱包装计算数量
                    Integer jssl = yqsl;
                    for (int j = 2;j >= 0 ;j--){
                        //循环获取包装 箱包装2  内包装1  主单位0
                        WmsPackingDetailed wmsPackingDetailed = packingDetailedList.get(j);
                        //主单位数量 箱包装2  内包装1  主单位0
                        Integer zdwsl = Integer.valueOf(wmsPackingDetailed.getZdwsl());
                        //如果不是主单位的情况下
                        if(j!=0 && zdwsl!=0){
                            //计算取整数
                            Integer number = jssl/zdwsl;
                            //遍历加入拆单列表
                            if(number>0){
                                for(int i = 0;i < number;i++){
                                    wmsSplit.setId(UUIDUtils.uuid());
                                    wmsSplit.setSsfymxid(wmsShipmentOrderDetailed.getId());
                                    wmsSplit.setHpid(wmsShipmentOrderDetailed.getHpid());
                                    wmsSplit.setSl(wmsPackingDetailed.getZdwsl());
                                    wmsSplit.setBzmxid(wmsPackingDetailed.getId());
                                    wmsSplit.setBzlx(String.valueOf(j));
                                    if(j == 2){
                                        wmsSplit.setZslx("0");
                                    }else{
                                        wmsSplit.setZslx("1");
                                    }
                                    wmsSplit.setC(wmsPackingDetailed.getC());
                                    wmsSplit.setK(wmsPackingDetailed.getK());
                                    wmsSplit.setG(wmsPackingDetailed.getG());
                                    wmsSplit.setTj(wmsPackingDetailed.getTj());
                                    wmsSplit.setBzzl(wmsPackingDetailed.getZl());
                                    wmsSplit.setFpzt("0");
                                    wmsSplit.setKwid(wmsShipmentOrderDetailed.getKwid().length()>0?wmsShipmentOrderDetailed.getKwid():null);
                                    wmsSplit.setPc(wmsShipmentOrderDetailed.getPc().length()>0?wmsShipmentOrderDetailed.getPc():null);
                                    wmsSplit.setScrq(wmsShipmentOrderDetailed.getScrq().length()>0?wmsShipmentOrderDetailed.getScrq():null);
                                    wmsSplit.setCkid(ckid);
                                    dao.baseInsertSelective(wmsSplit);
                                    jssl -= zdwsl;
                                }
                            }
                        }else{
                            //如果是主单位的情况下，并且剩余的数量不为0
                            if(jssl!=0){
                                wmsSplit.setId(UUIDUtils.uuid());
                                wmsSplit.setSsfymxid(wmsShipmentOrderDetailed.getId());
                                wmsSplit.setHpid(wmsShipmentOrderDetailed.getHpid());
                                wmsSplit.setSl("1");
                                wmsSplit.setBzmxid(wmsPackingDetailed.getId());
                                wmsSplit.setBzlx(String.valueOf(j));
                                wmsSplit.setZslx("1");
                                wmsSplit.setC(wmsPackingDetailed.getC());
                                wmsSplit.setK(wmsPackingDetailed.getK());
                                wmsSplit.setG(wmsPackingDetailed.getG());
                                wmsSplit.setTj(wmsPackingDetailed.getTj());
                                wmsSplit.setBzzl(wmsPackingDetailed.getZl());
                                wmsSplit.setFpzt("0");
                                wmsSplit.setKwid(wmsShipmentOrderDetailed.getKwid().length()>0?wmsShipmentOrderDetailed.getKwid():null);
                                wmsSplit.setPc(wmsShipmentOrderDetailed.getPc().length()>0?wmsShipmentOrderDetailed.getPc():null);
                                wmsSplit.setScrq(wmsShipmentOrderDetailed.getScrq().length()>0?wmsShipmentOrderDetailed.getScrq():null);
                                wmsSplit.setCkid(ckid);
                                dao.baseInsertSelective(wmsSplit);
                            }
                        }
                    }
                }
                //修改发运订单状态为已拆单
                wmsShipmentOrder.setCdzt("1");
                wmsShipmentOrderMapper.baseUpdateByPrimaryKeySelective(wmsShipmentOrder);

                //新增拆单历史
                WmsSplitHistory wmsSplitHistory = new WmsSplitHistory();
                wmsSplitHistory.setId(UUIDUtils.uuid());
                wmsSplitHistory.setSsfyddid(s);
                wmsSplitHistory.setCdr(cdr);
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                wmsSplitHistory.setCdsj(sdf.format(new Date()));
                wmsSplitHistory.setCzlx("0");
                wmsSplitHistory.setCkid(ckid);
                wmsSplitHistoryMapper.insert(wmsSplitHistory);
            }
            if(wcdIds.size()>0){
                dao.updateShipmentOrderCdzt(wcdIds);
            }
        for (String ycdId : ycdIds) {
              wmsShipmentOrder = wmsShipmentOrderMapper.selectById(ycdId);
            if(errMessage.length() > 0){
                errMessage.append("," + wmsShipmentOrder.getFybh());
            }else{
                errMessage.append(",失败单号：" + wmsShipmentOrder.getFybh());
            }
        }
        throw new SucessException("拆单操作，成功"+wcdIds.size()+ "条" + (ycdIds.size() > 0 ? "，失败"+ ycdIds.size() + "条"+errMessage.toString()+"请确定发运订单已审核且未拆单": ""));
    }



}
